package net.wanho.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.wanho.common.CaptchaConstants;
import net.wanho.dto.LoginDTO;
import net.wanho.exception.LoginException;
import net.wanho.mapper.LoginLogMapper;
import net.wanho.mapper.UserInfoMapper;
import net.wanho.po.LoginLog;
import net.wanho.po.UserInfo;
import net.wanho.service.LoginLogService;
import net.wanho.util.JwtUtil;
import net.wanho.vo.UserVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 32033
 * @description 针对表【login_log(系统登录日志)】的数据库操作Service实现
 * @createDate 2025-01-11 17:01:23
 */
@Service
@RequiredArgsConstructor
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements LoginLogService {


    // redisTemplate
    private final StringRedisTemplate redisTemplate;
    // userInfoMapper
    private final UserInfoMapper userInfoMapper;

    @Override
    public String login(LoginDTO loginDTO) {

        // 判断验证码
        // 获取redis中的验证码
        String key = CaptchaConstants.CAPTCHA_KEY + loginDTO.getUuid();
        String trueCode = redisTemplate.opsForValue().get(key);
        if (ObjectUtils.isEmpty(trueCode)) {
            throw new RuntimeException("验证码已过期");
        }
        // 删除验证码
        redisTemplate.delete(key);
        if (!trueCode.equalsIgnoreCase(loginDTO.getCode())) {
            throw new RuntimeException("验证码错误");
        }
//        UserInfo userInfo = userInfoMapper.selectByUserName(loginDTO.getUserCode());

        // 判断用户
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUserCode, loginDTO.getUserCode());
        wrapper.eq(UserInfo::getUserPwd, SecureUtil.md5(loginDTO.getUserPwd()));
        // 查询用户
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        // 判断用户是否被删除
        if (userInfo.getIsDelete().equals("1"))
            throw new LoginException("用户已被删除");
        // 判断用户是否被禁用
        if (userInfo.getUserState().equals("0"))
            throw new LoginException("用户已被禁用");
        // 密码校验
        if (!userInfo.getUserPwd().equals(SecureUtil.md5(loginDTO.getUserPwd())))
            throw new LoginException("密码错误");
        // 生成token
        Map<String, Object> payload = new HashMap<>();
        payload.put("userId", userInfo.getUserId());
        payload.put("userCode", userInfo.getUserCode());
        payload.put("userName", userInfo.getUserName());
        payload.put("userType", userInfo.getUserType());
        String token = JwtUtil.generate(payload);
        token = "Bearer " + token;

        Object Id = payload.get("userId");
        String userId = String.valueOf(Id);
        redisTemplate.opsForValue().set("token", userId, 12, TimeUnit.HOURS);
//        System.out.println(key);
//        System.out.println(payload.get("userId"));
        // 拼接token
        return token;

    }

    @Override
    public UserVo selectByUserId() {

        String userId = redisTemplate.opsForValue().get("token");
//        System.out.println(userId);

        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (userInfo == null)
            throw new LoginException("用户不存在");
        if (userInfo.getIsDelete().equals("1"))
            throw new LoginException("用户已被删除");
        if (userInfo.getUserState().equals("0"))
            throw new LoginException("用户已被禁用");
        UserVo userVo = new UserVo();
        userVo.setUserId(userInfo.getUserId());
        userVo.setUserCode(userInfo.getUserCode());
        userVo.setUserName(userInfo.getUserName());
        return userVo;
    }


}




